//
//  FXRefreshControl.swift
//  微博(Swift)
//
//  Created by V on 16/1/17.
//  Copyright © 2016年 V. All rights reserved.
//

import UIKit

enum FXRefreshControlState: Int {
    case Normal = 0         // 默认状态
    case Pulling = 1        // 松手就可以刷新的状态
    case Refreshing = 2     // 正在刷新状态
}
private let FXRefreshControlH: CGFloat = 50

class FXRefreshControl: UIControl {
    
    // MARK: - 懒加载
    // 剪头图标
    private lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    // 显示当前状态的 Label
    private lazy var messageLabel: UILabel = {
        let label = UILabel(textColor: UIColor.grayColor(), fontSize: 12)
        label.text = "下拉刷新"
        return label
        }()
    // 刷新中的状态控件
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView()
    // 刷新控件之前的状态
    var oldRefreshState: FXRefreshControlState = .Normal
    
    weak var scrollView: UIScrollView?
    var refreshState: FXRefreshControlState = .Normal {
        didSet {
            switch refreshState {
            case .Normal: // 默认状态：1.箭头变成原样 2.textLabel文字变化 3.隐藏状态图标 4.停止动画
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformIdentity
                })
                messageLabel.text = "下拉刷新"
                arrowIcon.hidden = false
                indicatorView.stopAnimating()
                // 只有从刷新状态到默认状态，才要把多出的滑动距离给减回去
                if oldRefreshState == .Refreshing {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        var contentInset = self.scrollView!.contentInset
                        contentInset.top = contentInset.top - FXRefreshControlH
                        self.scrollView!.contentInset = contentInset
                    })
                }
            case .Pulling: // 松手就开始刷新状态
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                messageLabel.text = "松开刷新"
            case .Refreshing: // 正在刷新状态
                indicatorView.isAnimating()
                arrowIcon.hidden = true
                messageLabel.text = "正在加载"
                // 调整contentInset的top值，让FXRefreshControl显示出来
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    var contentInset = self.scrollView!.contentInset
                    contentInset.top = contentInset.top + FXRefreshControlH
                    self.scrollView!.contentInset = contentInset
                })
                // 发送某个状态所在产生的事件
                sendActionsForControlEvents(UIControlEvents.ValueChanged)
            }
            // 记录状态，以便下一次再设置 refreshState 的时候，可以取到上一次的状态
            oldRefreshState = refreshState
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.frame.size = CGSize(width: SCREENW, height: 50)
        self.frame.origin.y = -self.frame.height
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        backgroundColor = RandomColor()
        addSubview(arrowIcon)
        addSubview(messageLabel)
        addSubview(indicatorView)
        
        // 添加约束
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(self)
            make.centerX.equalTo(self).offset(-30)
        }
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.centerY.equalTo(arrowIcon)
            make.leading.equalTo(arrowIcon.snp_trailing)
        }
        indicatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon)
        }
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        if let scrollView = newSuperview as? UIScrollView {
            self.scrollView = scrollView
            scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
        }
    }
    
    // 这个方法是当前控件观察的 scrollView 身上的 contentOffset 改变了之后，就会回调
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        // 判断 FXRefreshControl 是否完全显示出来
        let contentInsetTop = scrollView!.contentInset.top // 64
        // 当完全显示出来的时候
        let conditionValue = -contentInsetTop - FXRefreshControlH // 64 + 50
        // 判断是否用户在拖拽状态
        if scrollView!.dragging {
            // 拖拽的时候 
            // 1.是否全部显示出来了
            if scrollView!.contentOffset.y <= conditionValue && refreshState == .Normal {
                refreshState = .Pulling
                print("松手就可去刷新状态\(scrollView!.contentOffset.y)")
            }else if scrollView!.contentOffset.y > conditionValue && refreshState == .Pulling {
                refreshState = .Normal
                print("松手就自动回去，保持默认状态\(scrollView!.contentOffset.y)")
            }
        }else {
            // 松开的时候
            // 如果是 Pulling 状态就刷新
            if refreshState == .Pulling {
                refreshState = .Refreshing
                print("进入正在刷新状态")
            }
        }
        
    }
    
    
    // 移除观察者
    deinit {
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    
    
    // 停止刷新
    func endRefreshing(){
        refreshState = .Normal
    }

}
